#include "faceidentify.h"
#include "ui_faceidentify.h"
#include "loginwidget.h"
faceIdentify::faceIdentify(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::faceIdentify),
    stage(0)
{
    ui->setupUi(this);
    //设置登录界面
    setWindowTitle("登录成功");
    //实例化QTcpSocket
    socket = new QTcpSocket(this);

    //初始将开始按钮设置为可点击，停止不能点击
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);


    //信号关联槽函数
    connect(socket, SIGNAL(connected()), this, SLOT(connectSuccess()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectSuccess()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));


    //加载图片资源
    QPixmap pix;
    pix.load("../xust_displayImg/img/2.jpg");
    //给标签设置内容自适应标签大小
    ui->displayLable->setScaledContents(true);
    //将图片设置到标签上
    ui->displayLable->setPixmap(pix);
}

faceIdentify::~faceIdentify()
{
    delete ui;
}

void faceIdentify::on_returnButton_clicked()
{
    //关闭当前窗口
    this->close();
    //跳转登录窗口:给登录窗口发信号，登录窗口收到信号
    //再关联的槽函数里，将自己显示出来
    //信号触发方法：emit 信号()
    emit showLogin();//触发一个信号

}

void faceIdentify::on_startButton_clicked()
{
    //获取IP地址 + 端口号
    QString ip = ui->ipEdit->text();
    if(ip.isEmpty()) {
//        QMessageBox::warning(this, "警告，ip地址不能为空",);
        return;
    }
    QString port = ui->portEdit->text();
    if(port.isEmpty()) {
//        QMessageBox::warning(this, "警告，port不能为空");
        return;
    }
    //连接服务器
    socket->connectToHost(ip, port.toUInt());
}

void faceIdentify::connectSuccess()
{
    //连接成功
    stage = 1;
    //将开始按钮设置为不可点击，停止可点击
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);

}

void faceIdentify::disconnectSuccess()
{
    //将开始按钮设置为可点击，停止不可点击
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
}


void faceIdentify::on_stopButton_clicked()
{
    //断开与服务器的连接
    socket->disconnectFromHost();
    //加载图片资源
    QPixmap pix;
    pix.load("../xust_displayImg/img/2.jpg");
    //给标签设置内容自适应标签大小
    ui->displayLable->setScaledContents(true);
    //将图片设置到标签上
    ui->displayLable->setPixmap(pix);
}

int g_image_size = 0;
char g_image[300000];
void faceIdentify::readData()
{
    char buffer[256] = {0};
    //处于阶段1才能进行接收协议头
    if(stage == 1)
    {
        if(socket->bytesAvailable() < 7) return;
        //读取协议头数据
        socket->read(buffer, 7);
        //用#分割协议头字符串，得到图像数据长度
        QString head = buffer;
        QStringList list = head.split("#");
        g_image_size = list[0].toUInt();
        //阶段2代表可以开始接收图像数据
        stage = 2;
    }
    if(stage == 2)
    {
        if(socket->bytesAvailable() < g_image_size) return;
        //读取图像数据
        socket->read(g_image, g_image_size);
        //在标签上显示图像
        QPixmap pix;
        pix.loadFromData((const uchar*)g_image, g_image_size);
        ui->displayLable->setPixmap(pix);

        //阶段1可以开始接收协议头数据
        stage = 1;
    }
}



